import useClickOutside from "../hooks/useClickOutside";
import useIsomorphicLayoutEffect from "../hooks/useIsomorphicLayoutEffect";
import useKeyUp from "../hooks/useKeyUp";
import useLockScroll from "../hooks/useLockScroll";
import { FC, useRef } from "react";

interface ModalBodyProps {
  closeOnClickOutside: boolean;
  closeOnEscape: boolean;
  onToggle(): void;
}

const ModalBody: FC<ModalBodyProps> = ({
  children,
  closeOnClickOutside,
  closeOnEscape,
  onToggle,
}) => {
  const contentRef = useRef<HTMLDivElement>(null);

  useLockScroll();
  useKeyUp(27, () => closeOnEscape && onToggle());
  useClickOutside(closeOnClickOutside, contentRef, onToggle);

  useIsomorphicLayoutEffect(() => {
    const contentEle = contentRef.current;
    if (!contentEle) {
      return;
    }

    // Limit the height of modal content
    const maxHeight = document.body.clientHeight * 0.75;
    if (contentEle.getBoundingClientRect().height >= maxHeight) {
      contentEle.style.overflow = "auto";
      contentEle.style.maxHeight = `${maxHeight}px`;
    }
  }, []);

  return (
    <div className="rpv-core__modal-body" ref={contentRef}>
      {children}
    </div>
  );
};

export default ModalBody;
